/*
 * 作者：坚果派
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/address_provider.dart';
import '../../models/address_model.dart';
import 'dart:async';

class SearchTab extends StatefulWidget {
  const SearchTab({Key? key}) : super(key: key);

  @override
  State<SearchTab> createState() => _SearchTabState();
}

class _SearchTabState extends State<SearchTab> {
  final TextEditingController _searchController = TextEditingController();
  int _searchType = 1; // 默认搜索城市
  Timer? _debounce;

  @override
  void dispose() {
    _searchController.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  void _onSearchChanged(String value) {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      if (value.isNotEmpty) {
        Provider.of<AddressProvider>(context, listen: false)
            .searchAddress(_searchType, value);
      } else {
        Provider.of<AddressProvider>(context, listen: false)
            .clearSearchResults();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('搜索城市'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText: _searchType == 0 ? '输入省份名称' : '输入城市名称',
                    prefixIcon: const Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        _searchController.clear();
                        Provider.of<AddressProvider>(context, listen: false)
                            .clearSearchResults();
                      },
                    ),
                  ),
                  onChanged: _onSearchChanged,
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    const Text('搜索类型：'),
                    Radio<int>(
                      value: 0,
                      groupValue: _searchType,
                      onChanged: (value) {
                        setState(() {
                          _searchType = value!;
                        });
                      },
                    ),
                    const Text('省份'),
                    Radio<int>(
                      value: 1,
                      groupValue: _searchType,
                      onChanged: (value) {
                        setState(() {
                          _searchType = value!;
                        });
                      },
                    ),
                    const Text('城市'),
                    const Spacer(),
                    ElevatedButton(
                      onPressed: () {
                        if (_searchController.text.isNotEmpty) {
                          Provider.of<AddressProvider>(context, listen: false)
                              .searchAddress(_searchType, _searchController.text);
                        }
                      },
                      child: const Text('搜索'),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: Consumer<AddressProvider>(
              builder: (context, provider, child) {
                if (provider.loadingSearch) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (provider.searchError.isNotEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '搜索失败: ${provider.searchError}',
                          style: const TextStyle(color: Colors.red),
                          textAlign: TextAlign.center,
                        ),
                        const SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () {
                            if (_searchController.text.isNotEmpty) {
                              provider.searchAddress(
                                  _searchType, _searchController.text);
                            }
                          },
                          child: const Text('重试'),
                        ),
                      ],
                    ),
                  );
                }

                if (_searchController.text.isEmpty) {
                  return const Center(
                    child: Text('请输入搜索关键词'),
                  );
                }

                if (provider.searchResults.isEmpty) {
                  return const Center(
                    child: Text('未找到匹配的结果'),
                  );
                }

                return ListView.builder(
                  itemCount: provider.searchResults.length,
                  itemBuilder: (context, index) {
                    final province = provider.searchResults[index];
                    return _buildProvinceItem(province);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProvinceItem(Province province) {
    return ExpansionTile(
      title: Text(
        province.name,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text('编码: ${province.code}'),
      children: province.pchilds.map((city) => _buildCityItem(city)).toList(),
    );
  }

  Widget _buildCityItem(City city) {
    return Padding(
      padding: const EdgeInsets.only(left: 16.0),
      child: ExpansionTile(
        title: Text(city.name),
        subtitle: Text('编码: ${city.code}'),
        children: city.cchilds.map((district) => _buildDistrictItem(district)).toList(),
      ),
    );
  }

  Widget _buildDistrictItem(District district) {
    return Padding(
      padding: const EdgeInsets.only(left: 32.0),
      child: ListTile(
        title: Text(district.name),
        subtitle: Text('编码: ${district.code}'),
        dense: true,
      ),
    );
  }
}